import os
import time

from PySide6.QtCore import Qt
from PySide6.QtUiTools import QUiLoader

from tools.path_tool import PathTool



class ErrorLogView:
    def __init__(self, get_error, clear_error):
        self.__path_tool = PathTool()
        self.__error_log_view = QUiLoader().load(self.__path_tool.get_ui_path("error_log_view"))
        self.__error_log_view.setAttribute(Qt.WidgetAttribute.WA_QuitOnClose, False)
        self.__show_error_textEdit = self.__error_log_view.show_error_textEdit
        self.__clear_error = clear_error
        self.__get_error = get_error
        self.Desktop_path = os.path.join(os.path.expanduser("~"), "Desktop", f"unityError_{int(time.time())}.log.txt")
        self.__init_event()

    def __init_event(self):
        self.__error_log_view.clear_error_button.clicked.connect(self.clear_error_event)
        self.__error_log_view.refresh_error_button.clicked.connect(self.refresh_error_event)
        self.__error_log_view.save_error_button.clicked.connect(self.save_error_event)

    def ShowDialog(self):
        """
        展示窗口
        """
        text = self.__get_error()
        if not text:
            text = "【【【【【【【【暂无错误信息】】】】】】】】"
        self.__show_error_textEdit.setText(text)
        self.__error_log_view.show()

    def __print(self, ms):
        """
        窗口追加文本
        :param ms:需要追加的文本内容
        """
        self.__show_error_textEdit.append(ms.strip())

    def clear_error_event(self):
        """
        清空窗口文本，同时清理错误收集器中的信息
        """
        self.__show_error_textEdit.clear()
        self.__clear_error()

    def refresh_error_event(self):
        """
        展示最新的错误信息文本
        """
        text = self.__get_error()
        if not text:
            text = "【【【【【【【【暂无错误信息】】】】】】】】"
        self.__show_error_textEdit.setText(text)

    def save_error_event(self):
        """
        保存当前窗口展示的所有错误信息文本
        """
        text = self.__show_error_textEdit.toPlainText()
        if not text:
            self.__print("【【【【【【【【暂无错误信息】】】】】】】】")
            return
        try:
            with open(self.Desktop_path, "w", encoding="utf-8") as f:
                f.write(text)
            self.__print(f"日志文件已保存：{self.Desktop_path}")
        except Exception as e:
            for i in range(3):
                self.__print(f"【【【【【【【【！！！日志文件保存失败！！！】】】】】】】】")
            self.__print(str(e))
